import React, { useRef } from 'react';
import { ProTable, ActionType, ProColumns } from '@ant-design/pro-components';
import { message, Button } from 'antd';
import { RedoOutlined, ExceptionOutlined } from '@ant-design/icons';
import { downloadFile, saveDataParams, proTableRequest } from '@/app/common/utils';

import CreateForm from './CreateForm';
import EditDcitData from './EditDictData';

export type DictType = {
  dictId: number;
  dictName: string;
  status: number;
  dictType: string;
  remark: string;
};

const columns: ProColumns<DictType>[] = [
  {
    title: 'id',
    dataIndex: 'dictId',
    width: 48,
    search: false,
    editable: false,
  },
  {
    title: '字典名称',
    dataIndex: 'dictName',
    valueType: 'text',
    key: 'dictName',
  },
  {
    title: '字典类型',
    dataIndex: 'dictType',
    key: 'dictType',
    search: false,
    render: (_dom: React.ReactNode, entity, _index) => {
      return <EditDcitData text={_dom} entity={entity} />;
    },
  },
  {
    title: '状态',
    dataIndex: 'status',
    valueType: 'select',
    key: 'status',
    valueEnum: {
      0: {
        text: '正常',
        status: 'Success',
      },
      1: {
        text: '停用',
        status: 'Error',
      },
    },
  },
  {
    title: '创建人',
    width: 90,
    dataIndex: 'createBy',
    valueType: 'text',
    key: 'createBy',
    editable: false,
    search: false,
  },
  {
    title: '备注',
    dataIndex: 'remark',
    valueType: 'text',
    key: 'remark',
    ellipsis: true,
    search: false,
  },
  {
    title: '创建时间',
    key: 'createTime',
    dataIndex: 'createTime',
    valueType: 'dateTime',
    sorter: true,
    hideInSearch: true,
    editable: false,
  },
  {
    title: '操作',
    valueType: 'option',
    key: 'option',
    width: 120,
    render: (_text, record, _, action) => {
      return (
        <a
          key="dict-editable"
          onClick={() => {
            action?.startEditable?.(record.dictId);
          }}
        >
          编辑
        </a>
      );
    },
  },
];

// 字典管理
export default function Dict() {
  const actionRef = useRef<ActionType>();

  // 刷新缓存
  const refresh = async () => {
    const res = await $delete('/system/dict/type/refreshCache');
    console.log(res, '返回值啊');

    if (res.code === 200) {
      message.success('刷新缓存成功');
    }
  };

  return (
    <ProTable<DictType>
      columns={columns}
      actionRef={actionRef}
      request={proTableRequest('/system/dict/type/list')}
      editable={{
        type: 'multiple',
        onSave: async function(_key, record) {
          const res = await $put('/system/dict/type', { ...saveDataParams(record) });
          if (res.code === 200) {
            message.success('修改成功');
          }
          actionRef.current.reload();
        },
        onDelete: async function(_key) {
          const res = await $delete(`/system/dict/type/${_key}`);
          if (res.code === 200 && res.status === 200) {
            message.success('删除成功');
          }
        },
      }}
      rowKey="dictId"
      search={{
        labelWidth: 'auto',
      }}
      options={{
        setting: {
          listsHeight: 800,
        },
      }}
      form={{
        // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
        syncToUrl: (values, type) => {
          if (type === 'get') {
            return {
              ...values,
            };
          }
          return values;
        },
      }}
      pagination={{
        pageSize: 10,
      }}
      dateFormatter="string"
      headerTitle="字典类型"
      toolBarRender={action => [
        <CreateForm actionRef={action} key="dict-create" />,
        <Button type="primary" key="dict-refresh" icon={<RedoOutlined />} onClick={refresh}>
          刷新缓存
        </Button>,
        <Button
          key="dict-export"
          type="primary"
          icon={<ExceptionOutlined />}
          onClick={async () => {
            if (await downloadFile('/system/dict/type/export')) {
              message.success('下载成功');
            }
          }}
        >
          导出配置
        </Button>,
      ]}
    />
  );
}
